package com.prashantdctm.paidemail;

import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.gargoylesoftware.htmlunit.gae.GAEUtils;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlImageInput;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.prashantdctm.utils.EmailUtil;
import com.prashantdctm.utils.GeneralUtil;
import com.prashantdctm.utils.HttpUtil;

public class EmailPaysUServlet extends GaeHttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(EmailPaysUServlet.class.getName());
	
	public static void main(String[] args) throws Exception {
		EmailPaysUServlet p = new EmailPaysUServlet();webClient = HttpUtil.getWebClient();
		
		start("pk_jsp", "pk_995");
		//orkut();
		
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		super.doGet(req, resp);
		if(!isCron) {return;}
		
		stopWatch.reset();
		stopWatch.start();
		
		try {
			start("pk_jsp", "pk_995");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		stopWatch.stop();
		customLog("Time taken: " + stopWatch.toString());
		resp.getWriter().println(messageLog.toString());
		if (GAEUtils.isGaeMode()) {
			EmailUtil.sendEmail(messageLog.toString(), "sd");
		}
	}

	public static void start(String username, String pwd) throws Exception {
		HtmlPage page = null;

		try {
			page = webClient.getPage("http://www.e-mailpaysu.com/members/login.cgi?manzana");
			
			customLog("Logging in as " + username);
			webClient.waitForBackgroundJavaScript(5000);
			
			for (HtmlForm form : page.getForms()) {
				if (form.getAttribute("action").equals("http://e-mailpaysu.com/cgi-bin/password.cgi")) {
					form.getInputByName("USERNAME").setValueAttribute(username);
					form.getInputByName("PASSWORD").setValueAttribute(pwd);
					page = form.getInputByValue("Login").click();
					break;
				}
			}
		} catch (Exception e) {
			customException("Error in logging ", e);
			e.printStackTrace();
			return;
		}
		
		String 	checkMessageUrl = null;
		for(HtmlAnchor anchor: page.getAnchors()){
			if(anchor.getHrefAttribute().startsWith("http://e-mailpaysu.com/cgi-bin/viewstats.cgi")) {
				checkMessageUrl = anchor.getHrefAttribute(); 
			}
		}
		earningBefore = checkEarnings(checkMessageUrl);
		customLog("Checking current earning: " + earningBefore);
		
		for(HtmlAnchor anchor: page.getAnchors()){
			if(anchor.getHrefAttribute().startsWith("http://e-mailpaysu.com/cgi-bin/viewmail.cgi") && anchor.getHrefAttribute().contains("ViewMail")) {
				page = anchor.click();
				break;
			}
		}
		webClient.waitForBackgroundJavaScript(5000);
		
		for(HtmlAnchor anchor: page.getAnchors()){
			customLog(anchor.getTextContent()+" Clicked: "+anchor.getNextSibling().getTextContent());
			
			if(anchor.getTextContent().contains("Click for Credit") && anchor.getNextSibling().getTextContent().contains("Clicked No")) {
				customLog("Reading message ");
				page = anchor.click();
				Thread.sleep(30000);
			}
		}
		
		
		/*//customLog(page.asXml());
		((HtmlElement) page.getByXPath("//tr/td[text()='My Balance']/td/strong").get(0)).getTextContent();
		
		customLog("Checking current earning: " + earningBefore);
		

		customLog("Landed into inbox page, processing messages");
		// customLog(page.asXml());
		HtmlAnchor anchor = null;
		while (messagesRead < 10) {

			// check if message exists
			if ((anchor = HttpUtil.getAnchorContains(page, "members/email/")) != null) {
				messagesRead++;
				String messageId = anchor.getParentNode().getPreviousSibling()
						.getPreviousSibling().getFirstChild().getAttributes()
						.getNamedItem("value").getNodeValue();
				String subject = anchor.getFirstChild().getTextContent();
				String date = anchor.getParentNode().getNextSibling()
						.getTextContent();
				customLog("MessageId: " + messageId + " | Subject: " + subject
						+ " | Date: " + date);
				if (subject.startsWith("Survey Notification") || subject.startsWith("PaidEmail - Survey")) {
					try {
						customLog("This is a survey page, deleting message");
						//webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME
						// );
						webClient.waitForBackgroundJavaScript(3000);
						HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
								.getByXPath(
										"//input[@value='" + messageId + "']")
								.get(0);
						checkbox.click();
						page = page.getElementByName("delete").click();
					} catch (Exception e) {
						customLog(e.getMessage());
					}
					continue;
				}

				String advPageParams = anchor.getAttributes().getNamedItem("onclick").getNodeValue();
				String advUrl = null;
				StringTokenizer stk = new StringTokenizer(advPageParams, ",");
				if (stk.hasMoreTokens()) {
					stk.nextToken();
					advUrl = "http://www.sendearnings.com/members/emailbox/"
							+ stk.nextToken().trim() + "/"
							+ stk.nextToken().trim() + "/"
							+ stk.nextToken().replace("'", "").trim();
				}
				customLog("Formatting URL for adv page: " + advUrl);

				page = webClient.getPage(advUrl);
				// GeneralUtils.dumpPage(page);
				customLog("Entering adv page");
				// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
				webClient.waitForBackgroundJavaScript(3000);

				//different criteria for fetching adv href
				boolean messageSuccessfullyRead= false;
				for(HtmlAnchor anchor1: page.getAnchors()) {
					if(anchor1.getOnClickAttribute().startsWith("window.open")){
						anchor1.getFirstChild();
						HtmlElement img = (HtmlElement) anchor1.getFirstChild();
						customLog("Clicking image: src="+img.getAttribute("src"));
						img.click();
						Thread.sleep(5000);
						// now delete this message
						// now delete this message
						customLog("going to inbox to delete this message");
						page = webClient.getPage("http://www.sendearnings.com/mailbox");
						// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
						webClient.waitForBackgroundJavaScript(3000);
						customLog("Deleting email");
						HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
								.getByXPath("//input[@value='" + messageId + "']")
								.get(0);
						checkbox.click();
						page = page.getElementByName("delete").click();
						messageSuccessfullyRead = true;
						break; 
					} 
				}
				if(!messageSuccessfullyRead) {
					for(HtmlAnchor anchor1: page.getAnchors()) {
						if(anchor1.getHrefAttribute().startsWith("/mail/go")){
							anchor1.click();
							Thread.sleep(5000);
							// now delete this message
							customLog("going to inbox to delete this message");
							page = webClient.getPage("http://www.sendearnings.com/mailbox");
							// webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
							webClient.waitForBackgroundJavaScript(3000);
							customLog("Deleting email");
							HtmlCheckBoxInput checkbox = (HtmlCheckBoxInput) page
									.getByXPath("//input[@value='" + messageId + "']")
									.get(0);
							checkbox.click();
							page = page.getElementByName("delete").click();
							messageSuccessfullyRead = true;
							break; 
						} 
					}
				}
				if(!messageSuccessfullyRead) {
					customLog("Message not read, cannot find appropriate link to click");
				}
			} else {
				//check for 'mailbox empty' label
				try{
					HtmlElement emptyElement = (HtmlElement) page.getByXPath("//div[@class='mailbox_empty']/h3/i").get(0);
					customLog(emptyElement.getTextContent());
				} catch (Exception e) {
					customException("Expecting mailbox empty message but not found", e);
				}
				
				break;
			}
		}
		//earningAfter = checkInboxDollars();

		// page = HtmlUtil.getAnchorStartsWith(page, "/members/logout").click();

		customLog("Total messages read: " + messagesRead);
		customLog("Previous Earning: " + earningBefore);
		customLog("Current Earning: " + earningAfter);
		// logout
		customLog("Logging out: " + username);
		webClient.getPage("http://www.sendearnings.com/members/logout/true");*/
		
		webClient.closeAllWindows();
	}
	
	public static String checkEarnings(String url) throws Exception {
		HtmlPage page = webClient.getPage(url);
		List<HtmlElement> nodes = (List<HtmlElement>) page.getByXPath("//tr/td/font/b");
		String pointEarned = null;
		String totalEarned = null;
		
		for(HtmlElement node : nodes) {
			//System.out.println("node.getTextContent()" +node.getTextContent());
			if(node.getTextContent().contains("Total Points Earned:")) {
				pointEarned = "Total Points Earned:"+node.getParentNode().getParentNode().getNextSibling().getFirstChild().getTextContent().trim();
			}
			if(node.getTextContent().contains("Total Earned:")) {
				totalEarned = "Total Earned:"+node.getParentNode().getParentNode().getNextSibling().getFirstChild().getTextContent().trim();
			}
		}
		return pointEarned + " | "+totalEarned;
	}
	
}
